<template>
  <div class="book-market">
    <el-container>
      <!-- 顶部导航条 -->
      <el-header class="nav-header">
        <el-menu mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" router>
          <div class="logo">
            <i class="el-icon-reading"></i>
            校园二手书交易平台
          </div>
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item index="/market">书籍市场</el-menu-item>
          <el-menu-item index="/my-posts">我的发布</el-menu-item>
          <el-menu-item index="/messages">消息中心</el-menu-item>
        </el-menu>
      </el-header>

      <!-- 搜索和排序 -->
      <el-header>
        <div class="search-container">
          <el-input
            placeholder="搜索书籍..."
            v-model="searchQuery"
            class="search-input"
            prefix-icon="el-icon-search"
            clearable
            @keyup.enter.native="handleSearch"
          ></el-input>
          <el-select v-model="sortBy" placeholder="排序方式" class="sort-select" @change="handleSearch">
            <el-option label="最新发布" value="create_time_desc"></el-option>
            <el-option label="价格从高到低" value="price_desc"></el-option>
            <el-option label="价格从低到高" value="price_asc"></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleSearch" :loading="loading">
            <i class="el-icon-search"></i> 查询
          </el-button>
        </div>
      </el-header>

      <!-- 书籍列表 -->
      <el-main v-loading="loading" element-loading-text="加载中...">
        <el-row :gutter="30">
          <el-col :span="6" v-for="book in marketBooks" :key="book.id">
            <el-card :body-style="{ padding: '0px' }" shadow="hover" class="book-card">
              <div class="book-image-container">
                <img :src="book.imageUrl || '/default-book.png'" class="book-image" @error="handleImageError">
                <div class="book-overlay">
                  <el-button type="primary" size="small" @click="viewBookDetail(book.id)">
                    <i class="el-icon-view"></i> 查看详情
                  </el-button>
                </div>
              </div>
              <div class="book-info">
                <h4 class="book-title">{{ book.title }}</h4>
                <p class="book-author">作者：{{ book.author }}</p>
                <div class="book-meta">
                  <p class="price">¥{{ book.price.toFixed(2) }}</p>
                  <span class="condition">{{ book.bookCondition }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty v-if="marketBooks.length === 0" description="暂无相关书籍"></el-empty>

        <!-- 分页组件 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[8, 16, 24, 32]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'BookMarketPage',
  data() {
    return {
      searchQuery: '',
      sortBy: 'create_time_desc',
      marketBooks: [],
      loading: false,
      currentPage: 1,
      pageSize: 8,
      total: 0,
      loadingTimer: null
    }
  },
  methods: {
    handleSearch() {
      this.currentPage = 1
      this.fetchBooks()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.handleSearch()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchBooks()
    },
    //获取书籍市场数据
    fetchBooks() {
      // 清除之前的定时器
      if (this.loadingTimer) {
        clearTimeout(this.loadingTimer)
      }
      
      // 设置新的定时器，300ms后才显示loading
      this.loadingTimer = setTimeout(() => {
        this.loading = true
      }, 300)

      request.get('/api/books/list', {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          searchQuery: this.searchQuery,
          sortBy: this.sortBy
        }
      }).then(res => {
        if(res.data.code === 1) {
          this.marketBooks = res.data.data.list
          this.total = res.data.data.total
        } else {
          this.$message.error(res.data.msg || '查询失败')
        }
      }).catch(() => {
        this.$message.error('网络错误')
      }).finally(() => {
        this.loading = false
        if (this.loadingTimer) {
          clearTimeout(this.loadingTimer)
          this.loadingTimer = null
        }
      })
    },
    contactSeller(bookId) {
      this.$router.push(`/messages?bookId=${bookId}`)
    },
    viewBookDetail(bookId) {
      this.$router.push(`/book/${bookId}`)
    },
    handleImageError(e) {
      e.target.src = '/default-book.png'
    }
  },
  created() {
    this.fetchBooks()
  },
  beforeDestroy() {
    if (this.loadingTimer) {
      clearTimeout(this.loadingTimer)
    }
  }
}
</script>

<style scoped>
.book-market {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 15px;
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 300px;
}

.sort-select {
  width: 150px;
}

.book-card {
  margin-bottom: 25px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.book-image-container {
  position: relative;
  height: 450px;
  overflow: hidden;
}

.book-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.book-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.book-image-container:hover .book-overlay {
  opacity: 1;
}

.book-image-container:hover .book-image {
  transform: scale(1.1);
}

.book-info {
  padding: 16px;
}

.book-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
  height: 44px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-author {
  color: #909399;
  font-size: 14px;
  margin: 8px 0;
}

.book-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin: 0;
}

.condition {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

.el-button.el-button--mini {
  padding: 7px 12px;
  font-size: 12px;
}

.el-button.el-button--mini i {
  margin-right: 3px;
  font-size: 12px;
}

/* 导航条样式 */
.nav-header {
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  float: left;
  line-height: 60px;
  margin: 0 20px;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.logo i {
  margin-right: 10px;
  font-size: 24px;
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }
  .sort-select {
    width: 100%;
  }
  .book-card {
    margin-bottom: 15px;
  }
  .book-image-container {
    height: 250px;
  }
}
</style>